import api from '../../api';
import { message } from 'antd';
import config from '../../comps/business/tradingMarket/config';
import typeConfig from '../../comps/business/tradingDirect/config';
import typeOfTradeX from '../../routes/PortfolioMnt/BookkeepingMnt/typeOfTradeX.js';
import findKeyword from '../../routes/PortfolioMnt/BookkeepingMnt/findKeyword';
import { fixedNum } from '../../utils/utils';
import accounting from 'accounting';
import moment from 'moment';

export default {
  namespace: 'portfolioTrialM',
  state: {
    columns: [
      // 非标工作台交易试算表头
      {
        dataIndex: 'portfolioName',
        key: 'portfolioName',
        title: '产品组合',
        width: 229,
        render: (val) => {
          if (val) {
            return val;
          }
        },
      },
      {
        dataIndex: 'stockCode',
        key: 'stockCode',
        title: '证券代码',
        width: 232,
      },
      {
        dataIndex: 'assetType',
        key: 'assetType',
        title: '资产类型',
        width: 110,
        render: (val) => {
          if (val === null || val === undefined) {
            return;
          } else {
            return val;
          }
        },
      },
      {
        dataIndex: 'costPrice',
        key: 'costPrice',
        title: '成本价',
        type: 'money',
        render: (text, record) => {
          if (record.assetType == '现金' || record.assetType == null) {
            return;
          }
          if (text === null || text === undefined) {
            return '--';
          } else {
            return accounting.formatNumber(Number(text), 2);
          }
        },
      },
      {
        dataIndex: 'price',
        key: 'price',
        title: '最新价',
        type: 'money',
        render: (text, record) => {
          if (record.assetType == '现金' || record.assetType == null) {
            return;
          }
          if (text === null || text === undefined) {
            return '--';
          } else {
            return accounting.formatNumber(Number(text), 2);
          }
        },
      },
      {
        dataIndex: 'amount',
        key: 'amount',
        title: '持仓数量',
      },
      {
        dataIndex: 'adjustedMarketValue',
        key: 'adjustedMarketValue',
        title: '持仓市值',
        type: 'money',
        width: 140,
      },
      {
        dataIndex: 'adjustedWeight',
        key: 'adjustedWeight',
        title: '权重',
        type: 'rate',
        width: 80,
      },
      {
        dataIndex: 'adjustedYield',
        key: 'adjustedYield',
        title: '收益率',
        type: 'updownText',
        percent: true,
        width: 90,
      },
    ],
  },
  effects: {
    //获取交易列表
    *getList({ payload, callback }, { call, put, select }) {
      const res = yield call(api.portfolioTrial.getTradeList, payload);
      const columns = [
        {
          title: '日期',
          dataIndex: 'createdTs',
          key: 'createdTs',
          workStation: true,
          width: 110,
          render: (val) => <span>{moment(val).format('YYYY-MM-DD')}</span>,
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          key: 'productName',
          workStation: true,
          width: 180,
        },
        {
          title: '组合名称',
          dataIndex: 'portfolioInfoName',
          key: 'portfolioInfoName',
          width: 180,
        },
        {
          title: '证券代码',
          dataIndex: 'tradingCode',
          key: 'tradingCode',
          workStation: true,
          width: 180,
        },
        {
          title: '证券名称',
          dataIndex: 'tradingName',
          key: 'tradingName',
          width: 180,
        },
        {
          title: '交易市场',
          dataIndex: 'securityExchange',
          key: 'securityExchange',
          width: 120,
          render: (val, record) => {
            // 虚拟标没有交易市场
            if (record.type == 26) return '--';
            let trade = typeOfTradeX(record);
            if (trade) {
              let findvalue = config.filter((item) => {
                let value = trade.securityExchange ? trade.securityExchange : trade.exchangeCode;
                return item.selfValue == value || item.value == value;
              });
              if (findvalue && findvalue.length > 0) {
                return findvalue[0].title;
              } else {
                return '--';
              }
            }
          },
        },
        {
          title: '业务类型',
          dataIndex: 'type',
          key: 'type',
          width: 120,
          render: (val, record) => {
            let findType = typeConfig.filter((item) => {
              return item.value == record.type;
            });
            if (findType && findType.length > 0) {
              return findType[0].title;
            } else {
              return '--';
            }
          },
        },
        {
          title: '交易方向',
          dataIndex: 'orderSide',
          key: 'orderSide',
          workStation: true,
          width: 100,
          render: (val, record) => {
            if (record.type == 26) return '买入';
            // 根据业务类型，翻译交易方向
            let trade = typeOfTradeX(record);
            if (trade) {
              let findtypes = typeConfig.filter((item) => {
                return item.value == record.type;
              });
              if (findtypes && findtypes.length > 0) {
                let findorderSide = findtypes[0].tradingDirect.filter((item) => {
                  return item.value == findKeyword(trade, record, 'orderSide');
                });
                if (findorderSide && findorderSide.length > 0) {
                  return findorderSide[0].title;
                } else {
                  return '--';
                }
              } else {
                return '--';
              }
            }
          },
        },
        {
          title: '交易数量',
          dataIndex: 'tAmount',
          key: 'tAmount',
          type: 'number',
          workStation: true,
          width: 120,
          render: (val, record) => {
            // 去除测试问题
            // if (record.type == '26') {
            //   return record.trade26.orderQty || record.trade26.orderQty===0 ? accounting.formatNumber(record.trade26.orderQty) : '--';
            // }
            let trade = typeOfTradeX(record);
            if (record.type == '13') {
              if (trade.pledgeVo[0]) {
                return +trade.pledgeVo[0].transactionAmount / 100;
              } else {
                return '--';
              }
            }
            return findKeyword(trade, record, 'tAmount');
          },
        },
        {
          title: '价格（净价）',
          dataIndex: 'price',
          key: 'price',
          type: 'money',
          width: 120,
          render: (val, record) => {
            let trade = typeOfTradeX(record);
            if (record.type == '5') {
              if (trade.applyNum == null || trade.applyNum == undefined) {
                return '--';
              } else {
                return +trade.applyAmount / trade.applyNum;
              }
            }
            return findKeyword(trade, record, 'price', 'moneys');
          },
        },
        {
          title: '价格（全价）',
          dataIndex: 'amount',
          key: 'amount',
          type: 'money',
          workStation: true,
          className: 'column-right',
          width: 120,
          render: (val, record) => {
            // 全价在type26时=净价
            if (record.type == '26') {
              let trade = typeOfTradeX(record);
              if (record.type == '5') {
                if (trade.applyNum == null || trade.applyNum == undefined) {
                  return '--';
                } else {
                  return +trade.applyAmount / trade.applyNum;
                }
              }
              return findKeyword(trade, record, 'price', 'moneys');
            }
            let trade = typeOfTradeX(record);
            if (findKeyword(trade, record, 'amount', 'moneys')) {
              return findKeyword(trade, record, 'amount', 'moneys');
            } else {
              return fixedNum(val);
            }
          },
        },
        {
          title: '利率（%）',
          dataIndex: 'repoRate',
          key: 'repoRate',
          type: 'rate',
          className: 'column-right',
          width: 100,
          render: (val, record) => {
            if (record.type == 26) {
              return record.trade26.yield || record.trade26.yield == 0 ? Number(record.trade26.yield).toFixed(2) : '--';
            }
            let trade = typeOfTradeX(record);
            if (trade) {
              if (record.type == '7') {
                let num = findKeyword(trade, record, 'orderSide');
                if (num == 3 || num == 4) {
                  return;
                }
              }
              if (record.type === '8') {
                if (record.trade8.orderSize == 'F') {
                  return findKeyword(trade, record, 'repoRateF', 'rate');
                } else if (record.trade8.orderSize == 'i') {
                  return findKeyword(trade, record, 'repoRateI', 'rate');
                } else {
                  return '--';
                }
              }
            }
            return findKeyword(trade, record, 'repoRate', 'rate');
          },
        },
        {
          title: '交易金额',
          dataIndex: 'settlementAmount',
          key: 'settlementAmount',
          type: 'money',
          workStation: true,
          width: 120,
          className: 'column-right',
          render: (val, record) => {
            if (record.type == '26') {
              return record.trade26.amount || record.trade26.amount === 0 ? accounting.formatNumber(record.trade26.amount, 4) : '--';
            }
            let trade = typeOfTradeX(record);
            if (trade) {
              if (record.type === '8') {
                if (record.trade8.orderSize == 'F') {
                  return findKeyword(trade, record, 'settlementAmountF', 'rate');
                } else if (record.trade8.orderSize == 'i' || record.trade8.orderSize == 'calc') {
                  return findKeyword(trade, record, 'settlementAmountI', 'rate');
                } else {
                  return '--';
                }
              }
            }
            return findKeyword(trade, record, 'settlementAmount', 'money');
          },
        },
        {
          title: '清算速度',
          dataIndex: 'settlementSpeed',
          key: 'settlementSpeed',
          width: 100,
          render: (val, record) => {
            if (record.type == 26) return '--';
            let trade = typeOfTradeX(record);
            if (trade) {
              let newSettlementSpeed = findKeyword(trade, record, 'settlementSpeed');
              if (newSettlementSpeed == '1') {
                return 'T+0';
              }
              if (newSettlementSpeed == '2') {
                return 'T+1';
              }
              if (newSettlementSpeed == '0') {
                return 'T+0';
              }
            }
          },
        },
        {
          title: '交易对手',
          dataIndex: 'externalName',
          key: 'externalName',
          width: 160,
          render: (val, record) => {
            if (record.type == 26) return '--';
            let trade = typeOfTradeX(record);
            if (trade) {
              if (record.type === '1' || record.type === '2' || record.type === '3' || record.type === '4' || record.type === '16' || record.type === '25') {
                if (record.externalName === null || record.externalName === undefined) {
                  return '--';
                }
                return record.externalName;
              }
              return findKeyword(trade, record, 'externalName');
            }
          },
        },
      ];
      if (res && res.code == 0) {
        res.data &&
          res.data.dataSource.map((item) => {
            if (item.type == '17') {
              //中签状态 拿到外层 方便使用tableC操作按钮
              item.bondOffStatus = item.trade17.status;
            }
          });
        callback({
          pageInfo: {
            total: res.data.pageInfo.total,
            currentPage: res.data.pageInfo.currentPage,
            pageSize: res.data.pageInfo.numInPage,
          },
          dataSource: res.data.dataSource,
          columns: columns,
        });
      }
    },

    //删除交易记录
    *deleteTrade({ payload, callback }, { call, put }) {
      const res = yield call(api.portfolioTrial.deleteTrade, payload);
      if (res && res.code == 0) {
        callback(res.data);
      } else {
        message.error(res?.message);
      }
    },

    // 查询产品组/组合试算
    *getPortfolioList({ payload, callback }, { call, put, select }) {
      const response = yield call(api.portfolioTrial.getPortfolioList, payload);
      if (response?.code == 0) {
        callback(response.data);
      } else {
        callback('fail');
        message.error(response?.msg || '获取账户类型下拉列表失败');
      }
    },

    // 展开产品组/组合试算
    *selectPortfolioList({ payload, callback }, { call, put, select }) {
      const response = yield call(api.portfolioTrial.selectPortfolioList, payload);
      if (response) {
        callback(response.data);
      } else {
        callback('fail');
        message.error(response?.msg || '获取账户类型下拉列表失败');
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
